package cn.ug.activity.web.utils;

import cn.ug.activity.bean.CertificateBean;
import cn.ug.activity.bean.DisplayLinkParamBean;
import cn.ug.activity.bean.IdsBean;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.timevale.esign.sdk.tech.bean.OrganizeBean;
import com.timevale.esign.sdk.tech.bean.PersonBean;
import com.timevale.esign.sdk.tech.bean.PosBean;
import com.timevale.esign.sdk.tech.bean.SignPDFStreamBean;
import com.timevale.esign.sdk.tech.bean.result.AddAccountResult;
import com.timevale.esign.sdk.tech.bean.result.AddSealResult;
import com.timevale.esign.sdk.tech.bean.result.FileDigestSignResult;
import com.timevale.esign.sdk.tech.bean.result.Result;
import com.timevale.esign.sdk.tech.bean.seal.OrganizeTemplateType;
import com.timevale.esign.sdk.tech.bean.seal.PersonTemplateType;
import com.timevale.esign.sdk.tech.bean.seal.SealColor;
import com.timevale.esign.sdk.tech.impl.constants.OrganRegType;
import com.timevale.esign.sdk.tech.impl.constants.SignType;
import com.timevale.esign.sdk.tech.service.AccountService;
import com.timevale.esign.sdk.tech.service.EsignsdkService;
import com.timevale.esign.sdk.tech.service.SealService;
import com.timevale.esign.sdk.tech.service.SelfSignService;
import com.timevale.esign.sdk.tech.service.factory.AccountServiceFactory;
import com.timevale.esign.sdk.tech.service.factory.EsignsdkServiceFactory;
import com.timevale.esign.sdk.tech.service.factory.SealServiceFactory;
import com.timevale.esign.sdk.tech.service.factory.SelfSignServiceFactory;
import com.timevale.esign.sdk.tech.v3.service.TemplateSignService;
import com.timevale.esign.sdk.tech.v3.service.factory.TemplateSignServiceFactory;
import com.timevale.tech.sdk.bean.HttpConnectionConfig;
import com.timevale.tech.sdk.bean.ProjectConfig;
import com.timevale.tech.sdk.bean.SignatureConfig;
import com.timevale.tech.sdk.constants.AlgorithmType;
import com.timevale.tech.sdk.constants.HttpType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static cn.ug.util.ConstantUtil.*;

public class ESignHelper {
    private static Logger LOG = LoggerFactory.getLogger(ESignHelper.class);

    public static boolean initProject(String projectId, String projectSecret, String apiUrl) {
        ProjectConfig config = new ProjectConfig();
        config.setProjectId(projectId);
        config.setProjectSecret(projectSecret);
        config.setItsmApiUrl(apiUrl);
        HttpConnectionConfig httpConCfg = new HttpConnectionConfig();
        httpConCfg.setHttpType(HttpType.HTTPS);
        httpConCfg.setRetry(5);
        SignatureConfig sCfg = new SignatureConfig();
        sCfg.setAlgorithm(AlgorithmType.HMACSHA256);
        sCfg.setEsignPublicKey("");
        sCfg.setPrivateKey("");
        EsignsdkService sdk = EsignsdkServiceFactory.instance();
        Result result = sdk.init(config, httpConCfg, sCfg);
        if (0 != result.getErrCode()) {
            LOG.info("init project：errCode = {}, msg={} ", result.getErrCode(), result.getMsg());
            return false;
        } else {
            return true;
        }
    }

    public static String createPersonAccount(String mobile, String name, String idcard) {
        PersonBean personBean = new PersonBean();
		personBean.setMobile(mobile);
        personBean.setName(name);
        personBean.setIdNo(idcard);
        personBean.setPersonArea(0);
        AccountService accountService = AccountServiceFactory.instance();
        AddAccountResult addAccountResult = accountService.addAccount(personBean);
        if (addAccountResult == null || 0 != addAccountResult.getErrCode()) {
            LOG.error("create person account，errCode= {}, msg={}", addAccountResult.getErrCode(), addAccountResult.getMsg());
            return "";
        }
        return addAccountResult.getAccountId();

    }

    public static String createOrganizeAccount(String name, String organCode, String legalName, String legalIdcard) {
        OrganizeBean organizeBean = new OrganizeBean();
        organizeBean.setName(name);
        organizeBean.setOrganType(0);
        organizeBean.setRegType(OrganRegType.MERGE);
        organizeBean.setOrganCode(organCode);
        organizeBean.setUserType(2);
        organizeBean.setLegalName(legalName);
        organizeBean.setLegalArea(0);
        organizeBean.setLegalIdNo(legalIdcard);
        AccountService accountService = AccountServiceFactory.instance();
        AddAccountResult addAccountResult = accountService.addAccount(organizeBean);
        if (addAccountResult == null || 0 != addAccountResult.getErrCode()) {
            LOG.info("create organize account，errCode= {}, msg={}", addAccountResult.getErrCode(), addAccountResult.getMsg());
            return "";
        }
        return addAccountResult.getAccountId();
    }

    public static AddSealResult addPersonTemplateSeal(String accountId) {
        PersonTemplateType personTemplateType = PersonTemplateType.RECTANGLE;
        SealColor sealColor = SealColor.RED;
        SealService sealService = SealServiceFactory.instance();
        AddSealResult addSealResult = sealService.addTemplateSeal(accountId, personTemplateType, sealColor);
        if (addSealResult == null || 0 != addSealResult.getErrCode()) {
            LOG.error("创建个人模板印章失败，errCode=" + addSealResult.getErrCode() + " msg=" + addSealResult.getMsg());
            return null;
        }
        return addSealResult;

    }

    public static AddSealResult addOrganizeTemplateSeal(String accountId, String hText, String qText) {
        OrganizeTemplateType organizeTemplateType = OrganizeTemplateType.STAR;
        SealColor sealColor = SealColor.RED;
        SealService sealService = SealServiceFactory.instance();
        AddSealResult addSealResult = sealService.addTemplateSeal(accountId, organizeTemplateType, sealColor, hText, qText);
        if (addSealResult == null || 0 != addSealResult.getErrCode()) {
            LOG.error("创建企业模板印章失败，errCode=" + addSealResult.getErrCode() + " msg=" + addSealResult.getMsg());
            return null;
        }
        return addSealResult;
    }

    public static FileDigestSignResult padData(byte[] pdfFileStream, String accountId, String sealData, Map<String, Object> map) {
        SignPDFStreamBean signPDFStreamBean = setSignPDFStreamBean(pdfFileStream);
        TemplateSignService templateSignService = TemplateSignServiceFactory.instance();
        FileDigestSignResult fileDigestSignResult = templateSignService.streamSign(accountId, sealData, signPDFStreamBean, "signName", map);
        if (fileDigestSignResult == null || 0 != fileDigestSignResult.getErrCode()) {
            LOG.info("模板签署失败，errCode=" + fileDigestSignResult.getErrCode() + " msg=" + fileDigestSignResult.getMsg());
            return null;
        }
        return fileDigestSignResult;
    }

    public static FileDigestSignResult platformSignByStreamm(byte[] pdfFileStream) {
        SignPDFStreamBean signPDFStreamBean = setSignPDFStreamBean(pdfFileStream);
        //PosBean posBean = setXYPosBean("4",450,500);
        PosBean posBean = setXYPosBean("4",450,310);
        SignType signType = SignType.Single;
        int sealId = 0;
        SelfSignService selfSignService = SelfSignServiceFactory.instance();
        FileDigestSignResult fileDigestSignResult = selfSignService.localSignPdf(signPDFStreamBean, posBean, sealId, signType);
        if (0 != fileDigestSignResult.getErrCode()) {
            LOG.info("平台自身PDF摘要签署（文件流）失败，errCode=" + fileDigestSignResult.getErrCode() + " msg=" + fileDigestSignResult.getMsg());
            return null;
        }
        return fileDigestSignResult;

    }

    public static FileDigestSignResult platformSignByStreammSmooth(byte[] pdfFileStream) {
        SignPDFStreamBean signPDFStreamBean = setSignPDFStreamBean(pdfFileStream);
        //PosBean posBean = setXYPosBean("4",450,500);
        PosBean posBean = setXYPosBean("6",470,355);
        SignType signType = SignType.Single;
        int sealId = 0;
        SelfSignService selfSignService = SelfSignServiceFactory.instance();
        FileDigestSignResult fileDigestSignResult = selfSignService.localSignPdf(signPDFStreamBean, posBean, sealId, signType);
        if (0 != fileDigestSignResult.getErrCode()) {
            LOG.info("平台自身PDF摘要签署（文件流）失败，errCode=" + fileDigestSignResult.getErrCode() + " msg=" + fileDigestSignResult.getMsg());
            return null;
        }
        return fileDigestSignResult;

    }

    public static boolean saveSignedByStream(byte[] signedStream,String signedFolder,String signedFileName) {
        boolean isSuccess = false;
        Map<String,String> fileResult = saveFileByStream(signedStream, signedFolder,signedFileName);
        if (0 != Integer.parseInt(fileResult.get("errCode"))) {
            LOG.info("保存签署后文件失败，errCode=" + fileResult.get("errCode") + " msg=" + fileResult.get("msg"));
        } else {
            isSuccess = true;
        }
        return isSuccess;

    }

    public static Map<String, String> saveFileByStream(byte[] bytes, String folder, String fileName) {
        Map<String, String> fileResult = new HashMap<String, String>();
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(folder);
            if (!dir.exists() && dir.isDirectory()) {
                dir.mkdirs();
            }
            file = new File(folder + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            fileResult.put("errCode", "0");
            fileResult.put("msg", "保存签署后文件成功");
        } catch (Exception e) {
            LOG.info("保存签署后文件失败：" + e.getMessage());
            fileResult.put("errCode", "0");
            fileResult.put("msg", "保存签署后文件成功");
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                    LOG.info("保存签署后文件失败：" + e1.getMessage());
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                    LOG.info("保存签署后文件失败：" + e1.getMessage());
                }
            }
        }
        return fileResult;
    }

    /**
     *  定义所属行业类型
     * @param projectId
     * @param projectSecret
     * @param industry
     * @param busTypeUrl
     * @return
     */
    public static String createIndustryType(String projectId, String projectSecret, String industry, String busTypeUrl) {
        ArrayList<String> industries = new ArrayList<String>();
        industries.add(industry);
        JSONObject paramJson = new JSONObject();
        paramJson.put("name", industries);
        String signature = DigestHelper.getSignature(paramJson.toString(), projectSecret, ALGORITHM, UTF8);
        LinkedHashMap<String, String> headers = getPOSTHeaders(projectId, signature, ALGORITHM, CONTENT_TYPE, UTF8);
        JSONObject result = sendPOST(busTypeUrl, paramJson.toString(), headers, UTF8);
        if (result != null && result.getIntValue("errCode") == 0 && result.getJSONObject("result") != null) {
            Map<String, String> mapDate = JSONObject.parseObject(result.getString("result"), Map.class);
            if (mapDate != null) {
                for(Iterator<String> iterator = mapDate.keySet().iterator(); iterator.hasNext();){
                    String key = iterator.next();
                    return key;
                }
            }
        }
        LOG.info("[定义所属行业类型]接口返回json数据:" + result);
        return null;
    }

    public static String createSceneType(String projectId, String projectSecret, String businessTempletId, String scene, String sceneUrl) {
        ArrayList<String> scenes = new ArrayList<String>();
        scenes.add(scene);
        JSONObject paramJson = new JSONObject();
        paramJson.put("businessTempletId", businessTempletId);
        paramJson.put("name", scenes);
        String signature = DigestHelper.getSignature(paramJson.toString(), projectSecret, ALGORITHM, UTF8);
        LinkedHashMap<String, String> headers = getPOSTHeaders(projectId, signature, ALGORITHM, CONTENT_TYPE, UTF8);
        JSONObject result = sendPOST(sceneUrl, paramJson.toString(), headers, UTF8);
        if (result != null && result.getIntValue("errCode") == 0 && result.getJSONObject("result") != null) {
            Map<String, String> mapDate = JSONObject.parseObject(result.getString("result"), Map.class);
            if (mapDate != null) {
                for(Iterator<String> iterator = mapDate.keySet().iterator(); iterator.hasNext();){
                    String key = iterator.next();
                    return key;
                }
            }
        }
        LOG.error("[定义业务凭证（名称）]接口返回json数据:" + result);
        return null;
    }

    public static String createSegmentType(String projectId, String projectSecret, String sceneTempletId, String segment, String segTypeUrl) {
        ArrayList<String> segments = new ArrayList<String>();
        segments.add(segment);
        JSONObject paramJson = new JSONObject();
        paramJson.put("sceneTempletId", sceneTempletId);
        paramJson.put("name", segments);
        String signature = DigestHelper.getSignature(paramJson.toString(), projectSecret, ALGORITHM, UTF8);
        LinkedHashMap<String, String> headers = getPOSTHeaders(projectId, signature, ALGORITHM, CONTENT_TYPE, UTF8);
        JSONObject result = sendPOST(segTypeUrl, paramJson.toString(), headers, UTF8);
        if (result != null && result.getIntValue("errCode") == 0 && result.getJSONObject("result") != null) {
            Map<String, String> mapDate = JSONObject.parseObject(result.getString("result"), Map.class);
            if (mapDate != null) {
                for(Iterator<String> iterator = mapDate.keySet().iterator(); iterator.hasNext();){
                    String key = iterator.next();
                    return key;
                }
            }
        }
        LOG.info("[定义业务凭证中某一证据点名称]接口返回json数据:" + result);
        return null;
    }

    public static boolean createSegmentPropType(String projectId, String projectSecret, String segmentTempletId, ArrayList<DisplayLinkParamBean> segmentProp, String segpropUrl) {
        JSONObject paramJson = new JSONObject();
        paramJson.put("segmentTempletId", segmentTempletId);
        paramJson.put("properties", JSONArray.parseArray(JSONObject.toJSONString(segmentProp)));
        String signature = DigestHelper.getSignature(paramJson.toString(), projectSecret, ALGORITHM, UTF8);
        LinkedHashMap<String, String> headers = getPOSTHeaders(projectId, signature, ALGORITHM, CONTENT_TYPE, UTF8);
        JSONObject result = sendPOST(segpropUrl, paramJson.toString(), headers, UTF8);
        if (result != null && result.getIntValue("errCode") == 0) {
            return true;
        }
        LOG.info("[定义业务凭证中某一证据点的字段属性]接口返回json数据:" + result);
        return false;
    }

    public static PosBean setXYPosBean(String page,int x,int y) {
        PosBean posBean = new PosBean();
        posBean.setPosType(0);
        posBean.setPosPage(page);
        posBean.setPosX(x);
        posBean.setPosY(y);
        posBean.setWidth(159);
        return posBean;
    }

    public static SignPDFStreamBean setSignPDFStreamBean(byte[] pdfFileStream) {
        SignPDFStreamBean signPDFStreamBean = new SignPDFStreamBean();
        signPDFStreamBean.setStream(pdfFileStream);
        return signPDFStreamBean;
    }

    public static byte[] getBytes(String filePath) {
        File file = new File(filePath);
        byte[] buffer = null;
        try (FileInputStream fis = new FileInputStream(file)) {
            buffer = new byte[(int) file.length()];
            fis.read(buffer);
        } catch (FileNotFoundException e) {
            LOG.info("获取文件字节流失败：" + e.getMessage());
        } catch (IOException e) {
            LOG.info("获取文件字节流失败：" + e.getMessage());
        }
        return buffer;
    }

    public static String createChainOfEvidence(String sceneTemplateId, String sceneName, String projectId, String projectSecret, String voucherUrl) {
        JSONObject paramJson = new JSONObject();
        paramJson.put("sceneName", sceneName);
        paramJson.put("sceneTemplateId", sceneTemplateId);
        paramJson.put("linkIds", null);
        String signature = DigestHelper.getSignature(paramJson.toString(), projectSecret, ALGORITHM, UTF8);
        LinkedHashMap<String, String> headers = getPOSTHeaders(projectId, signature, ALGORITHM, CONTENT_TYPE, UTF8);
        JSONObject result = sendPOST(voucherUrl, paramJson.toString(), headers, UTF8);
        String evId = null;
        int errCode = result.getIntValue("errCode");
        if (0 == errCode) {
            evId = result.getString("evid");
            LOG.info("场景式存证编号 = " + evId);
        } else {
            LOG.error("创建证据链,获取场景式存证编号异常：errCode = " + errCode + " msg = " + result.get("msg"));
        }
        return evId;
    }

    public static void appendEvidence(String projectId, String projectSecret, String sceneEvId, String segmentEvId, String appendVoucherUrl, String signServiceId) {
        IdsBean ids0 = new IdsBean();
        ids0.setType("0");
        ids0.setValue(segmentEvId);
        IdsBean ids1 = new IdsBean();
        ids1.setType("1");
        ids1.setValue(signServiceId);
        ArrayList<IdsBean> linkIds = new ArrayList<IdsBean>();
        linkIds.add(ids0);
        linkIds.add(ids1);
        JSONObject paramJson = new JSONObject();
        paramJson.put("evid", sceneEvId);
        paramJson.put("linkIds", linkIds);
        String signature = DigestHelper.getSignature(paramJson.toString(), projectSecret, ALGORITHM, UTF8);
        LinkedHashMap<String, String> headers = getPOSTHeaders(projectId, signature, ALGORITHM, CONTENT_TYPE, UTF8);
        JSONObject result = sendPOST(appendVoucherUrl, paramJson.toString(), headers, UTF8);

        int errCode = result.getIntValue("errCode");
        if (0 == errCode) {
            boolean isAppendSuccess = result.getBoolean("success");
            LOG.info("追加证据点成功状态 = " + isAppendSuccess);
        } else {
            LOG.error("追加证据点异常：errCode = " + errCode + " msg = " + result.get("msg"));
        }
    }

    public static String getViewCertificateInfoUrl(String projectId, String projectSecret, String sceneEvId, String idcard, String viewpageUrl) {
        String timestampString = timestampString = dateToStamp("2100-12-31 23:59:59");
        String type = "ID_CARD";
        StringBuffer param = new StringBuffer();
        param.append("id=" + sceneEvId);
        param.append("&projectId=" + projectId);
        param.append("&timestamp=" + timestampString);
        param.append("&reverse=true");
        param.append("&type=" + type);
        param.append("&number=" + idcard);
        String signature = DigestHelper.getSignature(param.toString(), projectSecret, "HmacSHA256","UTF-8");
        String viewCertificateInfoUrl = viewpageUrl + "?" + param.toString() + "&signature=" + signature;
        return viewCertificateInfoUrl;
    }

    public static String dateToStamp(String dateTime) {
        String res = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date;
        try {
            date = simpleDateFormat.parse(dateTime);
            long ts = date.getTime();
            res = String.valueOf(ts);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return res;
    }

    public static void relateSceneEvIdWithUser(String projectId, String projectSecret, String sceneEvId, List<CertificateBean> certificates, String relateUrl) {
        JSONObject paramJson = new JSONObject();
        paramJson.put("evid", sceneEvId);
        paramJson.put("certificates", certificates);
        String signature = DigestHelper.getSignature(paramJson.toString(), projectSecret, ALGORITHM, UTF8);
        LinkedHashMap<String, String> headers = getPOSTHeaders(projectId, signature, ALGORITHM, CONTENT_TYPE, UTF8);
        JSONObject result = sendPOST(relateUrl, paramJson.toString(), headers, UTF8);

        int errCode = result.getIntValue("errCode");
        if (0 == errCode) {
            boolean isAppendSuccess = result.getBoolean("success");
            LOG.info("场景式存证编号关联到指定用户成功状态 = " + isAppendSuccess);
        } else {
            LOG.error("场景式存证编号关联到指定用户成功状态异常：errCode = " + errCode + " msg = " + result.get("msg"));
        }
    }

    public static JSONObject uploadOriginalDocumen(String evId, String fileUploadUrl, String filePath) {
        String ContentMD5 = DigestHelper.getContentMD5(filePath);
        String ContentType = "application/octet-stream";
        LinkedHashMap<String, String> headers = getPUTHeaders(ContentMD5, ContentType, UTF8);
        JSONObject result = sendPUT(evId, fileUploadUrl, filePath, headers);
        int errCode = result.getIntValue("errCode");
        if (200 == errCode) {
            LOG.info("存证环节编号= " + evId + " 待存证文档上传成功！");
        } else {
            LOG.error("存证环节编号= " + evId + " 待存证文档上传异常:Http状态码  = " + errCode + " msg = " + result.get("msg"));
        }
        return result;
    }

    public static JSONObject createSegmentOriginalStandard(String projectId, String projectSecret, String segmentData, String filePath, String segmentTempletId, String simulateUrl) {
        Map<String, String> fileInfo = getFileInfo(filePath);
        JSONObject contentJSON = new JSONObject();
        contentJSON.put("contentDescription", fileInfo.get("FileName"));
        contentJSON.put("contentLength", fileInfo.get("FileLength"));
        contentJSON.put("contentBase64Md5", DigestHelper.getContentMD5(filePath));
        JSONObject originalStdJSON = new JSONObject();
        originalStdJSON.put("segmentTempletId", segmentTempletId);
        originalStdJSON.put("segmentData", "\"" + segmentData + "\"");
        originalStdJSON.put("content", contentJSON);
        String signature = DigestHelper.getSignature(originalStdJSON.toString(), projectSecret, ALGORITHM, UTF8);
        LinkedHashMap<String, String> headers = getPOSTHeaders(projectId, signature, ALGORITHM, CONTENT_TYPE, UTF8);
        JSONObject result = sendPOST(simulateUrl, originalStdJSON.toString(), headers, UTF8);
        int errCode = result.getIntValue("errCode");
        if (0 == errCode) {
            String evId = result.getString("evid");
            String fileUploadUrl = result.getString("url");
            LOG.info("证据点ID= " + evId + " 待保全文档上传Url= " + fileUploadUrl);
        } else {
            LOG.error("获取证据点ID异常：errCode = " + errCode + " msg = " + result.get("msg"));
        }
        return result;
    }

    public static Map<String, String> getFileInfo(String filePath) {
        Map<String, String> fileInfo = new LinkedHashMap<String, String>();
        File file = new File(filePath);
        fileInfo.put("FileName", file.getName());
        fileInfo.put("FileLength", String.valueOf(file.length()));
        return fileInfo;
    }

    public static LinkedHashMap<String, String> getPOSTHeaders(String projectId, String signature, String algorithm, String ContentType, String encoding) {
        LinkedHashMap<String, String> headers = new LinkedHashMap<String, String>();
        headers.put("X-timevale-project-id", projectId);
        headers.put("X-timevale-signature", signature);
        headers.put("X-signature-algorithm", algorithm);
        headers.put("X-timevale-mode", "package");
        headers.put("Content-Type", ContentType);
        headers.put("Charset", encoding);
        return headers;
    }

    public static LinkedHashMap<String, String> getPUTHeaders(String ContentMD5, String ContentType, String encoding) {
        LinkedHashMap<String, String> headers = new LinkedHashMap<String, String>();
        headers.put("Content-MD5", ContentMD5);
        headers.put("Content-Type", ContentType);
        headers.put("Charset", encoding);
        return headers;
    }

    public static JSONObject sendPUT(String evId, String fileUploadUrl, String filePath, LinkedHashMap<String, String> headers) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            URL url = new URL(fileUploadUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("PUT");
            if (null != headers) {
                for (String key : headers.keySet()) {
                    httpURLConnection.setRequestProperty(key, headers.get(key));
                }
            }
            httpURLConnection.connect();
            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
            dos.write(getBytes(filePath));
            dos.flush();
            dos.close();
            int httpStatusCode = httpURLConnection.getResponseCode();
            String httpResponseMessage = httpURLConnection.getResponseMessage();
            obj = new JSONObject();
            if (HttpURLConnection.HTTP_OK == httpStatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
            } else {
                obj.put("errCode", httpStatusCode);
                obj.put("msg", "存证编号 = " + evId + " 的待保全文件上传失败！失败原因：" + httpResponseMessage);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static JSONObject sendPOST(String apiUrl, String data, LinkedHashMap<String, String> headers, String encoding) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("POST");
            if (null != headers) {
                for (String key : headers.keySet()) {
                    httpURLConnection.setRequestProperty(key, headers.get(key));
                }
            }

            httpURLConnection.connect();
            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
            dos.write(data.getBytes(encoding));
            dos.flush();
            dos.close();
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();
            obj = new JSONObject();
            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                LOG.info("http_StatusCode = " + http_StatusCode + " request_Parameter = " + data);
                obj = JSONObject.parseObject(strBuffer.toString());
            } else {
                obj.put("errCode", http_StatusCode);
                obj.put("msg", "请求失败！失败原因：" + http_ResponseMessage);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }
}
